package com.xhy.documents_collection.controller.caption;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.OperLog;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.entity.PO.task.Task;
import com.xhy.documents_collection.entity.PO.task.TaskTimingRecord;
import com.xhy.documents_collection.service.task.TaskService;
import com.xhy.documents_collection.service.task.TaskTimingRecordService;
import com.xhy.documents_collection.utils.R;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xhy
 * @since 2023-03-03
 * 定时任务管理
 */
@RestController
@RequestMapping("/caption/timings")
public class TaskTimingRecordController {

    @Resource
    TaskTimingRecordService taskTimingRecordService;

    @Resource
    TaskService taskService;

    // 获取所有定时任务
    @GetMapping
    @Authority("caption:timing:page")
    public R getTimingRecords(@RequestParam(value = "page") Long current,
                              @RequestParam(value = "limit") Long limit){

        Integer userId = UserHolder.get();
        Page<TaskTimingRecord> page = taskTimingRecordService.page(new Page<>(current, limit),
                new LambdaQueryWrapper<TaskTimingRecord>().eq(TaskTimingRecord::getUserId, userId).orderByDesc(TaskTimingRecord::getGmtCreated));
        List<Task> list = taskService.list(new LambdaQueryWrapper<Task>().eq(Task::getUId, userId).select(Task::getId, Task::getName, Task::getEndTime));
        HashMap<Integer, Task> taskMap = new HashMap<>();
        for (Task task : list) {
            taskMap.put(task.getId(),task);
        }
        for (TaskTimingRecord record : page.getRecords()) {
            Task task = taskMap.get(record.getTaskId());
            record.setTaskName(task.getName());
        }
        return R.ok().data("data",page.getRecords()).count(page.getTotal());
    }


    // 添加定时任务
    @PostMapping
    @Authority("caption:timing:add")
    @OperLog(title = ServiceType.SCHEDULER,businessType = BusinessType.INSERT)
    public R add(@RequestBody @Validated TaskTimingRecord taskTimingRecord){

        return taskTimingRecordService.addTask(taskTimingRecord);
    }

    // 修改定时任务
    @PutMapping
    @Authority("caption:timing:update")
    @OperLog(title = ServiceType.SCHEDULER,businessType = BusinessType.UPDATE)
    public R update(@RequestBody TaskTimingRecord taskTimingRecord){
        return taskTimingRecordService.updateTasks(Collections.singleton(taskTimingRecord));
    }

    // 删除定时任务
    @DeleteMapping("/{ids}")
    @Authority("caption:timing:delete")
    @OperLog(title = ServiceType.SCHEDULER,businessType = BusinessType.DELETE)
    public R delete(@PathVariable String ids){
        List<Integer> idList = Arrays.asList(ids.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
        return taskTimingRecordService.removeTaskByIds(idList);
    }

    // 手动发送定时任务
    @GetMapping("/artificial/send/{id}")
//    @Authority("caption:timing:artificial:send") // TODO 加到线上环境
    public R artificialSendEmail(@PathVariable Integer id){
        if (ObjectUtils.isEmpty(id)){
            return R.error().message("请选择定时任务");
        }
        taskTimingRecordService.artificialSend(id);
        return R.ok().message("发送成功");
    }
}

